package com.yanfei.zero.application.handler.exceptions;

import java.util.HashMap;
import java.util.Map;

import org.jboss.logging.MDC;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.async.AsyncRequestTimeoutException;

import io.swagger.v3.core.util.Json;
import lombok.extern.slf4j.Slf4j;
@RestControllerAdvice
@Slf4j
public class HandleValidationExceptions {
	
	
	@ExceptionHandler(MethodArgumentNotValidException.class)
	public Map<String, Object> handleValidationExceptions(
			MethodArgumentNotValidException ex) {
	    Map<String, Object> errors = new HashMap<>();
	    errors.put("code", HttpStatus.BAD_REQUEST.value());
	    StringBuffer sb = new StringBuffer();
	    ex.getBindingResult().getAllErrors().forEach((error) -> {
	        String fieldName = ((FieldError) error).getField();
	        String errorMessage = error.getDefaultMessage();
	        sb.append(fieldName+":"+errorMessage+";");
	    });
	    errors.put("msg", sb);
	    // 得到绑定的请求参数
		MDC.put("param", Json.pretty(ex.getBindingResult().getTarget()));
		log.error(ex.getLocalizedMessage(),ex);
	    return errors;
	}
	
	@ExceptionHandler(AsyncRequestTimeoutException.class)
	public void handleExceptions(
			AsyncRequestTimeoutException ex) {
		
		
		log.error("没有活动自动重试","测试自动重试");
	}
	
	@ExceptionHandler(Exception.class)
	public Map<String, Object> handleExceptions(
			Exception ex) {
		
		
		log.error(ex.getLocalizedMessage(),ex);
	    Map<String, Object> errors = new HashMap<>();
	    errors.put("code", HttpStatus.INTERNAL_SERVER_ERROR.value());
	   
	    errors.put("msg", "服务器内部异常,请联系管理员");
	    return errors;
	}
}
